package wang.lcs.pay;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wang.lcs.pay.util.print.LogHttpResult;

public class ErrorLogFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(ErrorLogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        try {
            chain.doFilter(request, response);
            int st = resp.getStatus() / 100;
            if (st == 2) {
            } else if (st == 4 || st == 5) {
                log.error("Run Error ! ruquest message : {} ", resp.getStatus());
                new LogHttpResult().print((HttpServletRequest) request, resp);
            }
        } catch (RuntimeException | IOException | ServletException e) {
            log.error("Request Error, extensions : [{}] {}", e.getClass().getName(), e.getMessage());
            new LogHttpResult().print((HttpServletRequest) request, resp);
            throw e;
        }
    }

    @Override
    public void destroy() {
    }

}